package com.yang.push.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {

    /**
     * 延迟交换机
     */
    public static final String DELAYED_EXCHANGE = "push_delayed_exchange";

    /**
     * 延迟队列
     */
    public static final String DELAYED_QUEUE = "push_delayed_queue";

    /**
     * 交换机的类型：延迟交换机
     * 与图形化界面选择的type要一直
     */
    private static final String DELAYED_EXCHANGE_TYPE = "x-delayed-message";

    /**
     * x-delayed-type交换机的通讯方式:fanout
     * key:x-delayed-type value:fanout
     */
    private static final String DELAYED_ROUTING_TYPE_KEY = "x-delayed-type";
    private static final String DELAYED_ROUTING_TYPE_FANOUT = "fanout";

    @Bean
    public Exchange delayedExchange(){
        //设置交换机属性，这里需要设置手动设置延迟交换机的类型
        //官方自带的交换机，是通过ExchangeBuilder的方法来创建交换机类型
        //而自定定义的交换机，必须通过key-value形式手动设置交换机的通讯方式
        //key:x-delayed-type vlue:通信方式   其中x-delayed-type固定的，value可以选择七种通信方式中的一种，目前为fanout
        Map<String,Object> args = new HashMap<>();
        args.put(DELAYED_ROUTING_TYPE_KEY,DELAYED_ROUTING_TYPE_FANOUT);

        //Exchange是接口，需要创建对应的实现类
        Exchange exchange = new CustomExchange(DELAYED_EXCHANGE,DELAYED_EXCHANGE_TYPE,true,false,args);
        return exchange;
    }

    @Bean
    public Queue delayedQueue(){
        //延迟队列本质还是普通的队列
        return QueueBuilder.durable(DELAYED_QUEUE).build();
    }

    @Bean
    public Binding delayedBinding(Queue delayedQueue,Exchange delayedExchange){
        //routingKey为空表示没有rountingKey
        return BindingBuilder.bind(delayedQueue).to(delayedExchange).with("").noargs();
    }
}
